package com.ruoyi.scale.rule;

import com.ruoyi.scale.document.ScaleLog;
import com.ruoyi.scale.document.Scale;
import com.ruoyi.scale.document.refs.ScaleDomainResult;
import com.ruoyi.scale.document.refs.ScaleResult;
import com.ruoyi.scale.document.refs.ScaleAnswer;
import com.ruoyi.scale.document.refs.ScaleDomainData;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 执行规则
 */
public interface EvalRule {
    /**
     * 执行量表
     *
     * @param scale
     * @param scaleLog
     * @return
     */
    ScaleResult eval(Scale scale, ScaleLog scaleLog);

    /**
     * 校验参数
     */
    default void prepare(ScaleLog scaleLog){

    }

    /**
     * 领域分支统计
     *
     * @param scale
     * @param scaleLog
     * @return
     */
    default List<ScaleDomainResult> collectDomainScore(Scale scale, ScaleLog scaleLog) {
        if(CollectionUtils.isEmpty(scale.getScaleDomainData())){
            return new ArrayList<>();
        }
        //初始化领域
        List<ScaleDomainResult> scaleDomainResults = scale.getScaleDomainData().stream().map(t -> {
            return ScaleDomainResult.builder()
                    .domainName(t.getName())
                    .questionNum(t.getQuestionNos().size())
                    .scaleDomainData(t).build();
        }).collect(Collectors.toList());

        for (ScaleAnswer scaleAnswer : scaleLog.getAnswerList()) {
            //分阶段统计
            for (ScaleDomainResult scaleDomainDatum : scaleDomainResults) {
                if (scaleDomainDatum.matchAnswer(scaleAnswer.getNo())) {
                    //累加分数
                    scaleDomainDatum.accrualScore(scaleAnswer.getScore());
                }
            }
        }
        //计算平均分
        for (ScaleDomainResult scaleDomainResult : scaleDomainResults) {
            scaleDomainResult.avg();
        }
        return scaleDomainResults;
    }
}
